package com.laicunba.service.jzh.impl;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.laicunba.constant.GloabConstant;
import com.laicunba.service.jzh.JzhRemoteBalanceService;
import com.laicunba.service.jzh.SecurityUtils;
import com.laicunba.util.HttpUtil;
import com.laicunba.util.StringUtil;

@Service
public class JzhRemoteBalanceServiceImpl extends JzhBaseService implements JzhRemoteBalanceService {
	private static final char SPLIT_CHAR = '|';
	private static SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMdd");

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List<RemoteBalanceResult> get(String custNos, long seq) {
		StringBuilder srcSign = new StringBuilder();
		String dt = SDF.format(new Date());

		String mchntTxnSsn = "Q" + Long.toString(System.currentTimeMillis()) + StringUtil.randomNumber(5) + String.format("%08d", seq);
		srcSign.append(custNos).append(SPLIT_CHAR);
		srcSign.append(GloabConstant.JZH_MCHNT_CD).append(SPLIT_CHAR);
		srcSign.append(dt).append(SPLIT_CHAR);
		srcSign.append(mchntTxnSsn);
		System.out.println(srcSign.toString());

		String signature = SecurityUtils.sign(srcSign.toString());
		Map param = new HashMap();
		param.put("mchnt_cd", GloabConstant.JZH_MCHNT_CD);
		param.put("mchnt_txn_ssn", mchntTxnSsn);
		param.put("mchnt_txn_dt", dt);
		param.put("cust_no", custNos);
		param.put("signature", URLEncoder.encode(signature));
		try {
			String xmlResult = HttpUtil.doPost(this.mchntURL + "/BalanceAction.action", param);
			Document doc = parseXml(xmlResult.getBytes("utf-8"));
			NodeList nodeList = getElementsByTagName(doc, "results");
			List resultList = new ArrayList();
			for (int i = 0; i < nodeList.getLength(); i++) {
				RemoteBalanceResult result = new RemoteBalanceResult();
				result.setUserId(getValue((Element) nodeList.item(i), "user_id"));
				result.setRespCode(getValue(doc, "resp_code"));
				result.setCaBalance(BigDecimal.valueOf(Double.parseDouble(getValue((Element) nodeList.item(i), "ca_balance"))).divide(BigDecimal.valueOf(100)));
				result.setCfBalance(BigDecimal.valueOf(Double.parseDouble(getValue((Element) nodeList.item(i), "cf_balance"))).divide(BigDecimal.valueOf(100)));
				result.setCtBalance(BigDecimal.valueOf(Double.parseDouble(getValue((Element) nodeList.item(i), "ct_balance"))).divide(BigDecimal.valueOf(100)));
				result.setCuBalance(BigDecimal.valueOf(Double.parseDouble(getValue((Element) nodeList.item(i), "cu_balance"))).divide(BigDecimal.valueOf(100)));
				resultList.add(result);
			}
			System.out.println(xmlResult);
			return resultList;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
